package com.aaa.springsecurity04.util;


import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.impl.JWTParser;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import netscape.javascript.JSUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    private static String sign="ykq-aaa";
    //1.生成jwt的token方法
    public static String createJWT(Map<String,Object> map){


        //定义头信息
        Map<String,Object> head=new HashMap<>();
        head.put("alg","HS256");
        head.put("typ","JWT");
        //定义颁发时间
        Date iat=new Date();
        //过期时间
        Calendar expire=Calendar.getInstance();
        expire.set(Calendar.SECOND,7200);
        Date expireTime=expire.getTime();


        String token=JWT.create()
                //头信息
                .withHeader(head)
                //设置颁发时间
                .withIssuedAt(iat)
                //设置过期时间
                .withExpiresAt(expireTime)
                //自定义的内容
                .withClaim("loginInfo",map)
                //签名
                .sign(Algorithm.HMAC256(sign));
        return token;
    }


    //2.校验token是否有效
    public static boolean verifyToken(String token){
        //获取一个JWT校验对象
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        try{
            //调用校验功能
            DecodedJWT verify = build.verify(token);
            return true;
        }catch (Exception e){
            System.out.println("token无效");
            return false;
        }
    }

    //3.从token中获取相关的载荷内容
    public static Map<String,Object> getTokenChaim(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        //调用校验功能
        DecodedJWT verify = build.verify(token);
        Claim loginInfo = verify.getClaim("loginInfo");
        return loginInfo.asMap();
    }

    public static void main(String[] args) {
        Map<String,Object> map=new HashMap<>();
        map.put("username","张三");
        map.put("sex","男");
        String jwt = createJWT(map);
        System.out.println(jwt);


        Map<String, Object> tokenChaim = getTokenChaim("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbkluZm8iOnsic2V4Ijoi55S3IiwidXNlcm5hbWUiOiLlvKDkuIkifSwiZXhwIjoxNjY3NDA1MDQwLCJpYXQiOjE2NjczOTc4OTl9.aE4tnnWMATNFQFAu-vrVT0FW4CLCXlbze25ZG2FpLhQ");
        System.out.println(tokenChaim);

    }
}
